package com.ruoyi.common.utils.qrCode;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closer;
import com.ruoyi.common.core.domain.entity.DownloadFile;
import com.ruoyi.common.core.domain.entity.EquAssetInfo;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * @ClassName QrCodeUtils
 * @Description TODO 图片工具类
 * @Author luguanqing
 * @Date 2021/7/12 10:29
 * @Version 1.0
 */
@Component
public class QrCodeUtils {

    private static final String FONT_TYPE = "宋体";

    private static String QRCODE_URL = "XX编号";

    /**
     * 生产资产管理二维码图片
     */
    public InputStream generateAssetsQrCodeImg(EquAssetInfo equInfo) throws IOException {
        //获取图片缓冲区(画布)
        BufferedImage bufferedImage = new BufferedImage(800, 400, BufferedImage.TYPE_INT_RGB);
        //获取画笔
        Graphics paint = bufferedImage.getGraphics();
        //设置画笔颜色
        paint.setColor(Color.white);
        //画布背景色
        paint.fillRect(0, 0, 800, 420);
        //生成二维码图片字节流
        byte[] qrCodeFile = QrCodeUtil.generatePng(equInfo.getEquNum(), 180, 180);
        return overlapImage(bufferedImage, qrCodeFile, equInfo);
    }

    /**
     * 图片重叠
     */
    public InputStream overlapImage(BufferedImage bufferedImage, byte[] qrCodeFile, EquAssetInfo equInfo) throws IOException {
        ByteArrayOutputStream os = null;
        InputStream qrCodeInputStream = null;
        try {
            BufferedImage qrCode = ImageIO.read(new ByteArrayInputStream(qrCodeFile));
            //背景图中写入信息
            Graphics2D g = bufferedImage.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            //公司名称
            g.setColor(Color.black);
            g.setFont(new Font(FONT_TYPE, Font.BOLD, 31));
            g.drawString("徐州矿一科技设备生命卡", 200, 40);
            //设备编号
            g.setColor(Color.black);
            g.setFont(new Font(FONT_TYPE, Font.BOLD, 31));
            if(StringUtils.isNotEmpty(equInfo.getEquNum())){
                g.drawString("设备编号：" + equInfo.getEquNum(), 80, 90);
            }else{
                g.drawString("设备编号：" + "", 80, 90);
            }
            //设备名称
            g.setColor(Color.black);
            g.setFont(new Font(FONT_TYPE,Font.BOLD,31));
            if(StringUtils.isNotEmpty(equInfo.getEquName())){
                g.drawString("设备名称：" + equInfo.getEquName(), 80, 150);
            }else{
                g.drawString("设备名称：" + "", 80, 150);
            }
            //设备型号
            g.setColor(Color.black);
            g.setFont(new Font(FONT_TYPE,Font.BOLD,31));
            if(StringUtils.isNotEmpty(equInfo.getEquModel())){
                g.drawString("设备型号：" + equInfo.getEquModel(), 80, 210);
            }else{
                g.drawString("设备型号：" + "", 80, 210);
            }
            //出厂编号
            g.setColor(Color.black);
            g.setFont(new Font(FONT_TYPE,Font.BOLD,31));
            if(StringUtils.isNotEmpty(equInfo.getEquNoOfpro())){
                g.drawString("出厂编号：" + equInfo.getEquNoOfpro(), 80, 270);
            }else{
                g.drawString("出厂编号：" + "", 80, 270);
            }
            //生产厂家
            g.setColor(Color.black);
            g.setFont(new Font(FONT_TYPE,Font.BOLD,31));
            if(StringUtils.isNotEmpty(equInfo.getEquManufacturer())){
                g.drawString("生产厂家：" + equInfo.getEquManufacturer(), 80, 330);
            }else{
                g.drawString("生产厂家：" + "", 80, 330);
            }
            //存放地点
            g.setColor(Color.black);
            g.setFont(new Font(FONT_TYPE,Font.BOLD,31));
            if(StringUtils.isNotEmpty(equInfo.getEquPlace())){
                g.drawString("存放地点：" + equInfo.getEquPlace(), 80, 390);
            }else{
                g.drawString("存放地点：" + "", 80, 390);
            }
            //在背景图片上添加二维码图片
            g.drawImage(qrCode, 650, 55, 128, 128, null);
            g.dispose();
            os = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", os);
            qrCodeInputStream = new ByteArrayInputStream(os.toByteArray());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(os != null){
                os.close();
            }
            if(qrCodeInputStream != null){
                qrCodeInputStream.close();
            }
        }
        return qrCodeInputStream;
    }


    /**
     * 资产二维码下载（包含文字信息）
     */
    public void messageQrCodeDownload(String filePath, java.util.List<EquAssetInfo> equInfoList) throws IOException {

        InputStream qrCodeInputStream = null;
        OutputStream outputStream = new FileOutputStream(filePath);
        try (Closer closer = Closer.create()) {
            //单个二维码导出
            if(equInfoList.size() == 1){
                qrCodeInputStream = generateAssetsQrCodeImg(equInfoList.get(0));
                closer.register(qrCodeInputStream);
//                String charset = "GB2312";
//                response.setCharacterEncoding(charset);
//                response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
//                String filename = new String(DISPLAYNAME.getBytes(charset), StandardCharsets.ISO_8859_1);
//                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
                int len;
                byte[] buffer = new byte[1000];
                while ((len = qrCodeInputStream.read(buffer)) != -1){
                    outputStream.write(buffer, 0, len);
                }
//                outputStream = closer.register(response.getOutputStream());
//                ByteStreams.copy(qrCodeInputStream, outputStream);
//                outputStream.flush();
            }

            //批量二维码导出
//            if(equInfoList.size()>1){
////                response.setContentType("application/zip");
////                response.setHeader("Content-Disposition", "attachment; filename=QrCodes.zip");
//                List<DownloadFile> downloadFiles =new ArrayList<>();
//                int i = 0;
//                for(EquInfo equInfo:equInfoList){
//                    i++;
//                    DownloadFile downloadFile = new DownloadFile();
//                    downloadFile.setFileName("XX二维码"+i+".png");
//                    downloadFile.setInputStream(generateAssetsQrCodeImg(equInfo));
//                    downloadFiles.add(downloadFile);
//                }
//                ZipUtil.toZip3(downloadFiles, response.getOutputStream());
//            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(qrCodeInputStream!=null){
                qrCodeInputStream.close();
            }
            if(outputStream!=null){
                outputStream.close();
            }
        }
    }

    /**
     * 资产二维码下载（包含文字信息）
     */
    public void messageQrCodeDownloadStream(HttpServletResponse response, java.util.List<EquAssetInfo> equInfoList) throws IOException {

        InputStream qrCodeInputStream = null;
        OutputStream outputStream = null;
        try (Closer closer = Closer.create()) {
            //单个二维码导出
            if(equInfoList.size() == 1){
                qrCodeInputStream = generateAssetsQrCodeImg(equInfoList.get(0));
                closer.register(qrCodeInputStream);
                String charset = "GB2312";
                response.setCharacterEncoding(charset);
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
                String filename = new String(equInfoList.get(0).getEquNum().getBytes(charset), StandardCharsets.ISO_8859_1);
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
                outputStream = closer.register(response.getOutputStream());
                ByteStreams.copy(qrCodeInputStream, outputStream);
                outputStream.flush();
            }

            //批量二维码导出
            if(equInfoList.size()>1){
                response.setContentType("application/zip");
                response.setHeader("Content-Disposition", "attachment; filename=QrCodes.zip");
                java.util.List<DownloadFile> downloadFiles =new ArrayList<>();
                int i = 0;
                for(EquAssetInfo equInfo:equInfoList){
                    i++;
                    DownloadFile downloadFile = new DownloadFile();
                    downloadFile.setFileName(equInfo.getEquNum()+".png");
                    downloadFile.setInputStream(generateAssetsQrCodeImg(equInfo));
                    downloadFiles.add(downloadFile);
                }
                ZipUtil.toZip3(downloadFiles, response.getOutputStream());
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(qrCodeInputStream!=null){
                qrCodeInputStream.close();
            }
            if(outputStream!=null){
                outputStream.close();
            }
        }
    }

    /**
     * 普通文件下载
     */
    public void imageDownload(HttpServletResponse response, InputStream inputStream, String fileName) throws IOException {
        OutputStream outputStream = new FileOutputStream("D:\\12312.png");
        try (Closer closer = Closer.create()) {
            closer.register(inputStream);
            String charset = "GB2312";
            response.setCharacterEncoding(charset);
            response.setContentType(MediaType.IMAGE_PNG.toString());
            String filename = new String(fileName.getBytes(charset), StandardCharsets.ISO_8859_1);
            int len;
            byte[] buffer = new byte[1000];
            while ((len = inputStream.read(buffer)) != -1){
                outputStream.write(buffer, 0, len);
            }
//            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
//            outputStream = closer.register(response.getOutputStream());
//            ByteStreams.copy(inputStream, outputStream);
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                inputStream.close();
            }
            if(outputStream!=null){
                outputStream.close();
            }
        }
    }

}
